package com.oopnet.template.test.google.cloud;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import com.google.cloud.AuthCredentials;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.BlobInfo.Builder;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Storage.BlobWriteOption;
import com.google.cloud.storage.Storage.CopyRequest;
import com.google.cloud.storage.Storage.SignUrlOption;


public class DatastoreExample {
	

	public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {

		Storage storage=null;
		System.out.println("Start Access To Google Storage...");
		try {
			//get storage object
			storage = StorageOptions.builder().authCredentials(AuthCredentials
					.createForJson(new FileInputStream(
							"/home/mercy/Downloads/mercy yang project 001-876c2dbb281a.json")))
					.build().service();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//list all buckets
		Bucket bucket =null;
		bucket = storage.get("mercy-yang-project-001.appspot.com");
		System.out.println("Access Successfully ！");
		
		System.out.println("\nBucket Name: "+bucket);
/*
		// List the blobs in a particular bucket
		Iterator<Blob> blobIterator = bucket.list().iterateAll();
		System.out.println("My blobs:");
		while (blobIterator.hasNext()) {
			System.out.println(blobIterator.next());
		}*/
		
		BlobId blobId = BlobId.of("mercy-yang-project-001.appspot.com", "upload/pdf/mercy.pdf");
		
		// upload doc
//		Blob blob = bucket.list().iterateAll().next();
//		System.out.println(blob);
		
		
		System.out.println("\nStart Upload Document To Google Storage...");
		BlobInfo info = BlobInfo.builder(blobId).contentType("application/pdf").build();
		Blob b2 = storage.create(info,new FileInputStream("/home/mercy/upload.pdf"));
//		storage.create(blobInfo, content, options)
//		Blob b2 = storage.create(info,new FileInputStream("/home/mercy/Downloads/doc/google cloud/google cloud install guide.html"));
		System.out.println("Upload Successful!"+" File Blob: \n"+b2);
		
		//delete doc
		
		/*
		Boolean flag = storage.delete(blobId);
		System.out.println(flag);*/
		
		//generate url
		System.out.println("\nGenerate Document URL:");
		Blob b = storage.get(blobId);
		URL url =  b.signUrl(10, TimeUnit.MINUTES);
		System.out.println(url.toString());
		
	}
}